type 'a graph_term = {nodes : 'a list;  edges : ('a * 'a) list};;

let neighbors g a cond =
  let edge l (b,c) = if b = a && cond c then c :: l
                    else if c = a && cond b then b :: l
                    else l in
  List.fold_left edge [] g.edges

let rec list_path g a to_b = match to_b with
| [] -> assert false (* [to_b] contains the path to [b]. *)
| a' :: _ ->
  if a' = a then [to_b]
  else
    let n = neighbors g a' (fun c -> not(List.mem c to_b)) in
    List.concat(List.map (fun c -> list_path g a (c :: to_b)) n)

(* 该算法通过查找从起始节点到其邻居的所有路径，然后将起始节点添加到每条路径末尾，从而构造出所有可能的环结构 *)
let cycles g a =
  (* 始终返回true的谓词函数,表示不限制邻居条件,n是节点a的所有邻居节点列表 *)
  let n = neighbors g a (fun _ -> true) in  
  let p = List.concat(List.map (fun c -> list_path g a [c]) n) in
  List.map (fun p -> p @ [a]) p;;

let example_graph =
  {nodes = ['b'; 'c'; 'd'; 'f'; 'g'; 'h'; 'k'];
    edges = [('h', 'g'); ('k', 'f'); ('f', 'b'); ('f', 'c'); ('c', 'b')]};;

cycles example_graph 'f';;